package com.shopping.servlets;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shopping.commons.LoginUtil;
import com.shopping.dao.CarDao;
import com.shopping.dao.FlowerDao;
import com.shopping.dao.impl.CarDaoImpl;
import com.shopping.model.Car;
import com.shopping.model.User;
import com.shopping.model.view.CarView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: CarServlet
 * @Description: TODO
 * @Author: JiaShiXi
 * @Date: 2021/3/20 15:00
 * @Version: 1.0
 **/
@WebServlet("/car/car.do")
public class CarServlet extends BaseServlet {

    CarDao carDao = new CarDaoImpl();

    /**
     * 添加商品到购物车
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void addCar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");

        //获得花卉编号和当前登录者信息（包含userId）
        int flowerId = Integer.parseInt(request.getParameter("flowerId"));

        if (user == null) {

            //获取所有Cookie的数组
            Cookie[] cookies = request.getCookies();

            //获得购物车的Cookie
            Cookie shopCartCookie = LoginUtil.unLoginAddCar(cookies, flowerId);

            //将购物车的Cookie添加到response
            response.addCookie(shopCartCookie);

            //跳转到查询购物车的servlet
            response.sendRedirect("/car/car.do?operate=queryCar");

            return;

        }

        //检测当前用户的购物车中是否包含flowerId所对应的花卉
        boolean mill = carDao.isContains(flowerId, user.getUser_id());

        if (mill) {//购物车中不存在当前添加的商品

            //添加新商品
            Car car = new Car();
            car.setFlower_id(flowerId);
            car.setCar_count(1);
            car.setUserId(user.getUser_id());
            carDao.addCar(car);
        } else {//购物车中存在当前商品

            //获取当前用户购物车中该商品的数量
            Integer carCount = carDao.getCountByUserIdAndFlowerId(user.getUser_id(), flowerId);

            //更新数量
            carDao.updateCount(flowerId, user.getUser_id(), carCount + 1);
        }

        //跳转到首页
        response.sendRedirect("/");
    }


    /**
     * 查询某个用户的购物车信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void queryCar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获得当前登录者对象
        User user = (User) request.getSession().getAttribute("user");

        if (user == null) {
            Cookie[] cookies = request.getCookies();
            List<CarView> carViewList = new ArrayList<>();
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("shopCart")) {
                    String jsonStr = URLDecoder.decode(cookie.getValue(), "utf-8");
                    List<Car> carList = JSONObject.parseArray(jsonStr, Car.class);
                    carViewList = LoginUtil.UnLoginCarTransfer(carList);
                }
            }
            //将carViewList存入到request对象中
            request.setAttribute("carViewList", carViewList);
            request.getRequestDispatcher("/showCar.jsp").forward(request, response);
            return;
        }
        //调用底层类中获取当前登录者的购物车信息方法
        List<CarView> carViewList = carDao.queryCar(user.getUser_id());

        //将carViewList存入到request对象中
        request.setAttribute("carViewList", carViewList);

        //请求转发到showCar.jsp
        request.getRequestDispatcher("/showCar.jsp").forward(request, response);
    }



//    /**
//     * 更新购物车的数量
//     *
//     * @param request
//     * @param response
//     * @throws ServletException
//     * @throws IOException
//     */
//    protected void updateCar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        int carId = Integer.parseInt(request.getParameter("carId"));
//        int count = Integer.parseInt(request.getParameter("count"));
//        //调用底层处理类对购物车中的数量进行更新
//        carDao.updateCount(carId, count);
//        //查询购物车
//        queryCar(request, response);
//    }


}
